#!/usr/bin/env ruby
# generates a google oauth refresh token

require_relative 'config'
require 'oauth2'

raise "Missing client_id variable" if Config::GDRIVE[:client_id].to_s.empty?
raise "Missing client_secret variable" if Config::GDRIVE[:client_secret].to_s.empty?
raise "Missing scope variable" if Config::GDRIVE[:scope].to_s.empty?

redirect_uri = 'https://localhost/usethistoken'

auth = OAuth2::Client.new(Config::GDRIVE[:client_id], Config::GDRIVE[:client_secret], {:site => 'https://accounts.google.com', :authorize_url => "/o/oauth2/auth", :token_url => "/o/oauth2/token"})

puts "1) Login to your Google Account then paste this URL into your browser\n\n"
puts auth.auth_code.authorize_url(:scope => Config::GDRIVE[:scope], :access_type => "offline", :redirect_uri => redirect_uri, :approval_prompt => 'force')

puts "\n\n\n2) Accept the authorization request from Google in your browser:"

puts "\n\n\n3) Google will redirect your browser, copy the code parameter out of the URL in your browser's location bar, then paste it here and hit enter:\n"
code = gets.chomp.strip

access_token_obj = auth.auth_code.get_token(code, { :redirect_uri => redirect_uri, :token_method => :post })

puts "Auth token: #{access_token_obj.token}"
puts "Refresh token: #{access_token_obj.refresh_token}"
